package com.mileage_tracker.util
{
	public class csv
	{
		public static function CSVtoarray(csvString:String):Array
		{
			csvString = split("\r\n").join("\n");
			var csvArray:Array = csvString.split("\n");

			for(var i:String in csvString)
			{
				var lineArray:Array = csvString[i].split(",");

				for(var j in lineArray)
				{
					lineArray[j] = lineArray[j].slice(1, lineArray[j].length - 1);
				}
				csvArray.push(lineArray);
			}
			return csvArray;
		}
		
		public static function CSVexport(dg:DataGrid, csvSeparator:String="\t", lineSeparator:String="\n"):String
		{
			var data:String = "";
			var columns:Array = dg.columns;
			var columnCount:int = columns.length;
			var column:DataGridColumn;
			var header:String = "";
			var headerGenerated:Boolean = false;
			var dataProvider:DataProvider = dg.dataProvider;
			var rowCount:int = dataProvider.length;
			var dp:Object = null;
			var j:int = 0;
			
			//loop through rows
			while (j<rowCount)
			{
				var obj:Object = null;
				obj = j;
				//loop through all columns for the row
				for (var k:int = 0; k < columnCount; k++)
				{
					column = columns[k];
					//Exclude column data which is invisible (hidden)
					if (!column.visible) continue;
			
					data += "\""+ column.itemToLabel(dg.getItemAt(j))+ "\"";
					trace(column.itemToLabel(dg.getItemAt(j))+"—-"+ data)
					if (k < (columnCount -1))
					{
						data += csvSeparator;
					}
					
					//generate header of CSV, only if it’s not genereted yet
					if (!headerGenerated)
					{
						header += "\"" + column.headerText + "\"";
						if (k < columnCount - 1)
						{
							header += csvSeparator;
						}
					}
				}
				headerGenerated = true;
				
				if (j < (rowCount - 1))
				{
					data += lineSeparator;
				}
				j++;
				//cursor.moveNext();
			}
			//set references to null:
			dataProvider = null;
			columns = null;
			column = null;
			return (header + "\r\n" + data);
		}
	}
}